/** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
**/

var currentScreen = null;
var tabsScroller = null;

var channelArray = null;

var rightMenu = null;

var cChannels = null;

var miniView = null;
var terms = null;
var help = null;
var search = null;

var miniViewItems = [];
var tabsArray = [];
var activeTab = null;
var lastRssDownloadTime = null;
var lastDownloadedResponse = "";

var sysinfo__ = null;

var wifionly = WLAN_ONLY_YES;

var documentBody = null;

var miniViewDisplayed = false;

var descriptionShown = false;
var descriptionEpisodesShown = false;
var episodesShown = false;
var searchShown = false;
var searchEpisodesShown = false;

//
// GENERAL: the setTimeout(func, 0) that you will see around in the code are in as workarounds for
// bugs. In general you can consider this as a "breather" given to the platform to either render or
// execute tasks correctly. Some may not be necessary on some platforms but might be on other. 
//

// jquery based init function - assign event listeners and init base screens and components
function init() {
	logDebug("Init started...");
	
	preLoadImages();
	pressurizeButtons();

	// Continue with startup.
	addSysInfo();
	
	wifionly = widget.preferenceForKey("wifionly") === 'true' ? true : widget.preferenceForKey("wifionly") === 'false' ? false : WLAN_ONLY_YES;
	
	OnlineMonitor.init();
	
	createRightMenu();
	
	// UI initialization
	cChannels = $("#whats_new");

	tabsScroller = new Scroller("tabs", "tabs_arrow_left", "tabs_arrow_right");
	
	miniView = new MiniView();
	terms = new Terms();
	
	get("logo_container").click ( function() {
		$("#tabs a:first").trigger("click");
	});
	
	// Show or hide debug output.
	if (DEBUG) {
		get("debug_view").removeClass("hidden");		

		// Start Platform Services monitoring.
		logDebug("Try to init Platform Services for device info...");
		initSystemServices();
	}
	
	//display default screen
	resize(true);
	
	// Set FL player
	get("screen_flash").html("<object id='swfObject' height='100%' width='100%' data='./" + FL_VIDEOPLAYER +
		"' allowscriptaccess='always' allowFullScreen='true' usefullscreen='true' type='application/x-shockwave-flash' loop='false' name='swfObject'><param name=\"canHandleException\" value=\"true\" /></object>");

	//setup connection monitor
	logDebug("Try to setup ConnectionMonitor...");
	ConnectionMonitor.startMonitorForNetwork(updateNetworkStatus);
	updateNetworkStatus();
};

function isContentDowloaded() {
	return tabsArray.length > 0;
}

/* N8 "pressed" state extension to jQuery (use CSS class .pressed)

   NB! Works only for anchor (<a>) elements, that are added to DOM as strings
   (i.e. in .html files or via some innerHTML= such as $("<a href..>...</a>") in
   jQuery.) It WON'T work with document.createElement("a"), use $("<a href...") instead.
   Also, you MUST set the href= attribute to some non-zero length value (such as "#")
   (but NOT "javascript:...") or the browser won't dispatch the correct events.

   You CAN:
    + set 'display: block' in CSS
    + append arbitary child elements
    + bind arbitary functions with jQuery or from HTML onClick=
   and the elements' feedback should still work, more or less. */
jQuery.fn.pressurize = function(){
    this.each(function(){
        var that = $(this);
		
		that.click(function(){
            that.removeClass("pressed");
        });
    	that[0].onmouseenter = function (e) { 
			that.addClass("pressed");
			setTimeout(function() {
				that.removeClass("pressed");
			}, 500);
		};
		that[0].onmousemove = function (e) { 
			that.addClass("pressed");
			setTimeout(function() {
				that.removeClass("pressed");
			}, 500);
		};
		that[0].onmouseout = function (e) { 
			that.removeClass("pressed");
		};
    });
    return this;
};

function preLoadImages() {
	ImagePreloader.add([
		"img/active-tab-bg.png",
		"img/arrow-left.png",
		"img/arrow-right.png",
		"img/arrow-right-disabled.png",
		"img/arrow-left-disabled.png",
		"img/back-arrow.png",
		"img/back-arrow-active.png",
		"img/btn-info.png",
		"img/btn-info-active.png",
		"img/btn-generic.png",
        "img/btn-generic-active.png",
		"img/connection-2g.png",
		"img/connection-3g.png",
		"img/connection-none.png",
		"img/connection-offline.png",
		"img/connection-wifi-3g.png",
		"img/header-button-close.png",
        "img/header-button-close-active.png",
		"img/header-button-menu.png",
        "img/header-button-menu-active.png",
		"img/main-area-top.png",
		"img/overlay-channel.png",
		"img/overlay_play.png",
		"img/tab-bg.png",
		"img/video-bg.png"
	]);
	ImagePreloader.start();	
}

function pressurizeButtons(){
    $("#exit_button_splash").pressurize();
    $("#exit_button").pressurize();
    $("#right_menu").pressurize();
    $("#search_btn").pressurize();
    $("#terms_btn").pressurize();
    $("#terms_exit_btn").pressurize();
    $("#btn_hide_description").pressurize();
    $("#btn_hide_episodes").pressurize();
    $("#alert_ok").pressurize();
    $("#alert_cancel").pressurize();
    $("#btn_hide_search").pressurize();
}

function resize (initResize) {
	
    if (initResize) $(window).resize(function(eventObject){
		resize(false)
	} );

	if (!isMiniView() && currentScreen) {
        if (currentScreen.attr("id") == "screen_flash" ) {
            widget.setDisplayLandscape();
            return;
        }
        if (currentScreen.attr("id") == "video_container") {
            /* Unnecessary resize event - do nothing */
            return;
        }
    }
	
	if ( isMiniView() ) {
		logDebug("Switching to Home Screen");
		
		// Went to miniview mode
		miniViewDisplayed = true;
		
		gotoScreen("screen_mv");
		showSplash( false );
		miniView.show();
		
	} else {
		
		logDebug("Switching to Full Screen");
		
		document.getElementById("splash_img").style.display='inline-block'
		
		// remember miniview current item, when we call hide it set currentItem to null
	    var miniViewItem = miniView.currentItem;
		miniView.hide();
		
		var showScreen = function() {
			
			if (terms.isAccepted() && UPDATE_URL && (!versionLastUpdateTime || (UPDATE_INTERVAL && versionLastUpdateTime + UPDATE_INTERVAL < new Date().getTime()))) {
				if (OnlineMonitor.isOnline()) {
					versionLastUpdateTime = new Date().getTime();	
					downloadUpdateTxt(UPDATE_URL);
				}
			}
			
			if( !isContentDowloaded() ) {
				gotoScreen("video_container");
			} else {
				gotoScreen("video_container");
				if( miniViewItem ) {
					selectItem( miniViewItem );
				}
			}
			
			showSplash(false);
			
		}
		
		var termsAccepted = function(){
			
			showSplash(true);
			rightMenu.selectTab();
			
			if (!OnlineMonitor.isOnline() && miniViewDisplayed) {
				// MiniView was displayed and Homescreen in offline mode				
				// Show offline info and exit
				Alert.show( str_player_no_connection , exit, null, str_soft_menu_exit);
				return;
			}
			
			if (!isContentDowloaded()) {
				downloadRss(RSS_URL, showScreen, null, true);
			}
			else {
				showScreen();
			}
		}
		
		if(!terms.isAccepted()) {		
			terms.show(termsAccepted);
		} else {
			termsAccepted();
		}
	}
}

function selectItem( obj ) {
	if( !obj || !obj.genres || !obj.genres.length ) { 
		return; 
	}
	
	var selectCorrectItem = function() {
		get("items_container").find("td .item").each( function() {
			var element = $(this);
			var item = element.data("item");
			if ( item == obj ) {
				element.trigger("click");
				return false;
			}
		});
	}
	
	// first select right tab
	for( var i=0; i < tabsArray.length; i++ ) {
		var currentTab = tabsArray[i] 
		if( currentTab.title == obj.genres[0].title ) {
			activateTab( currentTab.tab, selectCorrectItem );
		}
	}
}

function createRightMenu() {
	rightMenu = new RightMenu("right_menu", "popup_menu", "popup_menu_container", "soft_menu_buttons");
	rightMenu.enableAnimation(ENABLE_RIGHT_MENU_ANIMATION);
	
	if (typeof str_soft_menu_search != "undefined") {
		search = new Search();
		rightMenu.addButton(str_soft_menu_search, function(){
			rightMenu.hide();
			search.show();
		}, 'img/menu-icon-search.png');
	}

	if (typeof str_soft_menu_ovi != "undefined") {
		rightMenu.addButton(str_soft_menu_ovi, function(){
			rightMenu.hide(true);
			widget.openURL(OVI_STORE_LINK);
		}, 'img/menu-icon-ovi.png');
	}
	
	if (typeof str_soft_menu_wifi != "undefined") {
		rightMenu.addButton(str_soft_menu_wifi, function(){
			rightMenu.hide(false);
			toggleWifiOnly(false);
		}, 'img/menu-icon-wifi.png', true, 'toggle_wifi', wifionly);
	}
	
	if (typeof str_soft_menu_help != "undefined"){
		rightMenu.addButton(str_soft_menu_help, function(){
			rightMenu.hide();
			Alert.show(str_help + '<br/><br/>v.' + VERSION);
		}, 'img/menu-icon-about.png');
	}
}

function toggleWifiOnly(hideMenu) {
	if (!hideMenu)
		rightMenu.show();
		
	wifionly = !wifionly;
	
	if (wifionly) {
		get('toggle_wifi').text(str_soft_menu_wifi + ' ' + str_toggle_on);	
	} else {
		get('toggle_wifi').text(str_soft_menu_wifi + ' ' + str_toggle_off);
	}
	
	widget.setPreferenceForKey(wifionly + '', "wifionly");
}

function getDocumentBody() {
	if (documentBody == null) {
		documentBody = $("body");
	}
	
	return documentBody;
}

function gotoScreen(screenId){
	logDebug("gotoScreen screen to: " + screenId);
	if (screenId == "screen_flash") {
		getDocumentBody().addClass("body_fullscreen");
		
		removeSysInfo();
		if (!OnlineMonitor.isOnline()) {
			Alert.show(str_player_no_connection);
			return;
		}
	
		//check for 2G
		if (videoPlayAllowed()) {
			rightMenu.disable();
			
			switchScreen(screenId);
		} else {
			Alert.show(str_alert_low_connection + (wifionly ? "<br/>" + str_no_wlan_found : ""));
		}
	} else {
		getDocumentBody().removeClass("body_fullscreen");
		
		if (!sysinfo__) {
			addSysInfo();
		}
		setTimeout(function(){
			rightMenu.enable();
		}, 150);
		switchScreen(screenId);
	}	
}

function switchScreen(screenId){
	logDebug("Switching to screen to: " + screenId);

	var newScreen = get(screenId);	
	if(newScreen)
	{
		if (currentScreen) {
			if (currentScreen.attr("id") == "video_container") {
				currentScreen.data("tabs_scroll", document.getElementById("tabs").scrollLeft);
				currentScreen.data("items_scroll", document.getElementById("items_scroller").scrollLeft);
				var episodes_scroller = $("#items_container .episodes_scroller");
				currentScreen.data("episodes_scroll", episodes_scroller.length ? episodes_scroller[0].scrollTop : null);
			}
			currentScreen.addClass("hidden");
		}
		currentScreen = newScreen;
		currentScreen.removeClass("hidden");
		
		if(screenId == "video_container") {
			if(currentScreen.data("tabs_scroll")) document.getElementById("tabs").scrollLeft = currentScreen.data("tabs_scroll");
			if(currentScreen.data("items_scroll")) document.getElementById("items_scroller").scrollLeft = currentScreen.data("items_scroll");
			if (currentScreen.data("episodes_scroll")) {
				var episodes_scroller = $("#items_container .episodes_scroller");
				if (episodes_scroller.length) {
					episodes_scroller[0].scrollTop = currentScreen.data("episodes_scroll");
				}
			}
			tabsScroller.update();
		}
		
		currentScreen.focus();
	}
}

var downloadRssInProgress = null;
function downloadRss(rssURL, callback, selectedTabTitle, dontCheckTerms ) {	
	if (rssURL == downloadRssInProgress) {
		logDebug("Download already in progress, dropping this request. rssURL: " + rssURL);
		return;
	}
	lastRssDownloadTime = new Date().getTime();
	var onError = function(XMLHttpRequest, textStatus, errorThrown) {
		
		if (!isMiniView() && !OnlineMonitor.isOnline()) {
			Alert.show(str_player_no_connection, exit, null, str_soft_menu_exit);
			return;
		}		
		
		if(!lastDownloadedResponse) {
			lastDownloadedResponse = widget.preferenceForKey("chachedResponse");
		}
		
		if (lastDownloadedResponse) {
			logDebug("Download failed, fetch from cache");
			var xml=new DOMParser().parseFromString(lastDownloadedResponse, "text/xml");
			handleXmlResponse(xml, textStatus, selectedTabTitle);
		}
		else {
			logDebug("Download failed, show alert");
			if (!isMiniView()) {
				Alert.show(str_error_download + (XMLHttpRequest && XMLHttpRequest.status != 200 ? (XMLHttpRequest.status + " " + (XMLHttpRequest.statusText ? XMLHttpRequest.statusText : "")) : ""), exit);
			}
		}
	
		if (callback) { callback(); } 
	}
	
	//terms not accepted and not in MiniView
	if ((!dontCheckTerms && !terms.isAccepted() && !isMiniView)) {
		onError();
		return;
	}
	
	//offline
	if (!OnlineMonitor.isOnline()) {
		onError();
		return;
	}
	
	var onSuccess = function (response, status) {
		logDebug("Download succeeded, start parsing RSS...");
		if(!response) {
			onError({status: 0, statusText : ""});
			return;
		}
		
		try {
			var xml=new DOMParser().parseFromString(response, "text/xml");
			handleXmlResponse(xml, status, selectedTabTitle);
			try {
				widget.setPreferenceForKey(response, "chachedResponse");
			} catch (e) {}
			lastDownloadedResponse = response;
			
			logDebug("Parsing succeeded");
		} catch( err ) {
			logDebug("Parsing failed, show alert");
			Alert.show( str_error_rss + ": " + err);
		} 
		
		if (callback) { callback(); } 
	}
	
	logDebug("Starting to download RSS: " + rssURL);
	downloadRssInProgress = rssURL;	
	try {
		// Enable Universal Browser Read for running in desktop browser
		if (netscape.security.PrivilegeManager.enablePrivilege) 
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {		
	}
	$.ajax({
		type: "GET",
		url: rssURL,
		cache: rssURL.match(/^https?:\/\//) ? false : true,
		contentType: "text/plain",
		dataType: "text",
		beforeSend: function(){
			showLoader(true);
		},
		complete: function(){
			showSplash(false);
			showLoader(false);
		},
		success: function(response, status){
			downloadRssInProgress = null;
			onSuccess(response, status);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			downloadRssInProgress = null;
			onError(XMLHttpRequest, textStatus, errorThrown);
		}
	});
}

function handleXmlResponse(xml, textStatus, selectedTabText) {
	tabsArray = RSS.getTabsFromRss(xml);

	var clickableTab = renderTabs(tabsArray, selectedTabText);
	if(clickableTab)
		activateTab(clickableTab);
		
	return true;
}


function highlight(obj, callback) {
	obj.addClass("pressed");
	setTimeout(function () { obj.removeClass("pressed"); if(callback) callback(); }, 50);
}

function showSplash( show ) {
	if( show ) {
		get("static_startup").removeClass("hidden");
	} 
	else {
		get("static_startup").addClass("hidden");
	}		
}

function showLoader(show){
	if (show) {
		if (isMiniView()) {
			// show-hide miniview loader.		
			if (!miniViewItems || !miniViewItems.length) 
				get("mv_loader").removeClass("hidden");
		}
	}
	else {
		get("mv_loader").addClass("hidden");
	}
}

function showDescription(item) {
	descriptionShown = true;
	
	toggleBack(true);
	
	get('description_title').text(item.title);
	
	if (item.info) {
		get('description_subtitle').text(item.info);
	} else {
		get('description_subtitle').empty();
	}
	
	if (item.duration) {		
		get('description_duration').text(item.duration);
	} else {
		get('description_duration').empty();
	}
	
	get('description_text').text(item.description);
	
	var div = get('description_img');
	div.empty();
	
	if (item.image) {
		var img = createThumbnail(item, div[0]);
		div.append(img);			
	}
	
	div.unbind('click').click ( function(){
		
		if(item.items && item.items.length) { //episodes
			showEpisodes(null, item);
		}
		else  { //without episodes
		
			if (item && item.videos && item.videos.length) {
				var link = item.videos[0].link;
				playVideo(item);
				gotoScreen("screen_flash");
			}
		}
	});
	
	get('description_left').prepend(div);
	
	get('episodes_screen').addClass("hidden");
	get('whats_new').addClass('hidden');
	get('description_screen').removeClass('hidden');
	toggleTabs(false);
}

function hideDescription() {
	if (descriptionShown && !episodesShown) toggleBack(false);
	descriptionShown = false;
	
	get('description_screen').addClass('hidden');
	if (episodesShown) {
		get("episodes_screen").removeClass("hidden");
	} else {
		get('whats_new').removeClass('hidden');		
		toggleTabs(true);
	}
}

function toggleTabs(show) {
	if (show) {
		get('tabs').removeClass('hidden');
		get('tabs_arrow_left').removeClass('hidden');
		get('tabs_arrow_right').removeClass('hidden');
	} else {
		get('tabs').addClass('hidden');
		get('tabs_arrow_left').addClass('hidden');
		get('tabs_arrow_right').addClass('hidden');
	}	
}

function toggleBack(showBack) {
	if (showBack) {
		$('#exit_button').hide();
		$('#right_menu').hide();
	} else {
		$('#exit_button').show();
		$('#right_menu').show();
	}
	
}

function handleItemClick(element, episode, leaveHidden, triggered) {
	
	if (descriptionShown) return;
	
	var obj = $(element);
	
	var item = obj.data("item");
	
	if(episode && !leaveHidden)
		obj.find(".item_desc").removeClass("hidden");
	
	if(obj.hasClass("selected") && item && item.items && item.items.length) { //episodes
		$("#items_container div.selected").removeClass("selected");
		$("#items_container div.trigger").removeClass("trigger");
		setTimeout(function() { obj.addClass("selected"); }, 0);
		if(triggered) setTimeout(function() { obj.addClass("trigger"); }, 0);
		if (!obj.data("episodesShown")) {
			obj.data("episodesShown", true);
			showEpisodes(obj, item);
		} else {
			obj.data("episodesShown", false);
		}
	}
	else  { //without episodes
	
		if(obj.hasClass("selected")) {
			
			if (item && item.videos && item.videos.length) {
				highlight(obj);
				
				var link = item.videos[0].link; 
				playVideo(item, episode);
				gotoScreen("screen_flash");
			}
		} else {
			$("#items_container .selected").removeClass("selected");
			$("#items_container .trigger").removeClass("trigger");
			obj.addClass("selected");
			if(triggered) setTimeout(function() { obj.addClass("trigger"); }, 0);
		}
	}
}

function selectFirstTab() {
	activateTab(tabsArray[0].tab);
}

function activateTab(tab, callback, triggered, isSearch){
	
	activeTab = tab;
	
    if (!isSearch) {
        hideDescription();
        search.hide();
    }
	
	setTimeout(function(){ //give it some tome otherwise N5800 crashes
        clearSelectedTabs();
        tab.addClass("selected");
        
        if (!isSearch) {
            search.hide();
            var items = tab.data("items");
            var container = get("items_container");
            container.empty();
        }
		
		if (SCROLL_SPEED == 0) {
			
				setTimeout(function() {
					fillItems(tab, items);
					if (callback) 
						callback();
				}, 100);
						
		} else {
			Scroller.itemScrollIntoView(tab[0], document.getElementById("tabs"), triggered ? SCROLL_SPEED_KEYNAV : SCROLL_SPEED, function(){
				if (!isSearch) fillItems(tab, items);
				if (callback) 
					callback();
			});
		}		
	}, 0);
}

function clearSelectedTabs() {
	$("#tabs a.selected").removeClass("selected");
	$("#tabs a.pressed").removeClass("pressed");
}

function needRefresh() {
	return ((lastRssDownloadTime + RSS_DOWNLOAD_INTERVAL) < new Date().getTime());
}

function fillItems(tab, items){	
	var container = get("items_container");
	
	cChannels.removeClass("hidden");
	
	tab.data("down", null);
	
	if (!items || !items.length) 
		return;
	
	var l = items.length;
	
	var prev = null;
	var a = null;
	
	var last = null;
	
	addItem(items, 0, container, last, tab, prev);
}

function addItem(items, i, container, last, tab, prev) {	
	
	var renderItem = function() {
		var item = items[i];
		
		a = document.createElement('div');
		a.setAttribute('class', 'item vibra');		
		$(a).data("item", item);
		
		a.onclick = function(evt, triggered){			
			var wasSelected = $(this).hasClass("selected");
			
			var item_image = $(evt.target).closest("div.item_image");
			if (wasSelected && evt.target != this && !$(this).data("item").isChannel && !item_image.length) {
				return;
			}
			
			handleItemClick(this, null, null, triggered);
			var self = this;
			Scroller.itemScrollIntoView(this, document.getElementById("items_scroller"), triggered ? SCROLL_SPEED_KEYNAV : SCROLL_SPEED, function(){
				
				if (wasSelected) 
					return;
				
				if (item_image.length) {
					handleItemClick(self, null, null, triggered);
				}
			});
		};
		
		var imageDiv = document.createElement('div');
		imageDiv.setAttribute('id', 'item_image_'+ i);
		imageDiv.setAttribute('class', 'item_image');
		
		if (item.image) {
			imageDiv.appendChild(createThumbnail(item, imageDiv));
		}		
		
		var html = '<div class="item_title">';
		html += (item.title ? truncateText(item.title, 26) : "unknown title");
		html += '</div>';
		
		if (item.info) {
			html += '<div class="item_subtitle">';
			html += item.info;
			html += '</div>';
		}
		
		
		a.innerHTML = html;
		a.appendChild(imageDiv);
		
		if (item.duration) {
			var durDiv = document.createElement('div');
			durDiv.setAttribute('class', 'item_duration');
			durDiv.innerHTML = item.duration;
			a.appendChild(durDiv);
		} else if (item.isChannel && item.items) {
			var durDiv = document.createElement('div');
			durDiv.setAttribute('class', 'item_duration');
			durDiv.innerHTML = item.items.length;
			a.appendChild(durDiv);
		}
		
		if (item.description) {
			var descButton = $('<a class="btn_description btn_view_description vibra" href="#"></a>');
			descButton.pressurize();
			descButton.click(function() { showDescription(item); });
			a.appendChild(descButton[0]);
		}
		
		var td = $('<td>');
		td.append(a);
		
		if (tab == activeTab)
			container.append(td);
		
		if (i != items.length - 1 && tab == activeTab)
			addItem(items, i+1, container, last, tab, prev);
	}
	
	if (tab == activeTab) {
		renderItem();
	}
	
	if (i ==  items.length - 1)	{
	
		document.getElementById("items_scroller").scrollLeft = 0;
		
		// do we need refresh?
		if (needRefresh()) {
			downloadRss(RSS_URL, null, tab.data("title"));
			return;
		}
	}
}

function createThumbnail(item, imageDiv) {
	var img;
			
	if (!OnlineMonitor.isOnline()) {
		img = document.createElement('img');
		img.setAttribute('class','img_error');
	} else {
		img = document.createElement('img');
		img.style.visibility = "hidden";
		img.onload = function() { img.style.visibility = "visible"; }
		img.src = item.image;
		
		if (FORCE_IMAGE_SCALE) {
			img.setAttribute('class','force_resize');
		}
	}
	
	if (item.isChannel){
		var channelBadge = document.createElement('div');
		channelBadge.setAttribute('class','channel_badge');
		imageDiv.appendChild(channelBadge);
	} else {
		var playBadge = document.createElement('div');
		playBadge.setAttribute('class','play_badge');
		imageDiv.appendChild(playBadge);
	}
	
	return img;
}

function showEpisodes(obj, item, search) {
	
	if (searchShown && !search) {
		searchEpisodesShown = true;
	}
	
	var container = get("episodes_container");
	container.empty();
	
	if (!item.items || !item.items.length) 
		return;
	
	var l = item.items.length;
	
	var prev = null;
	var a = null;
	
	var last = null;
	
	get("episodes_title").html(item.title);
	
	addItem(item.items, 0, container, last, activeTab, prev);
	
	get('whats_new').addClass('hidden');
	toggleTabs(false);
	get("episodes_screen").removeClass("hidden");
	
	toggleBack(true);
	
	episodesShown = true;
}

function hideEpisodes() {
	
	if (!descriptionShown) {
		get('whats_new').removeClass('hidden');
		toggleTabs(true);
		toggleBack(false);
	}
	
	get("episodes_screen").addClass("hidden");
	
	episodesShown = false;
	
	if (searchEpisodesShown) {
		//return to search results
		showEpisodes(null, search.getSearchResults(), true);
	} else {
		searchShown = false;		
	}
	
	searchEpisodesShown = false;
}

function renderTabs(tabsArray, selectedTabTex) {
	var tabs = get("tabs");
	tabs.empty();
	
	var firsClickableTab = null;
	
	var prev = null;
	var a = null;
	
	var l = tabsArray.length;
	for(var i=0; i<l; i++) {
		var t = tabsArray[i];
		
		if(t.deleted) continue;
		
		a = $('<a class="top_button vibra" href="#"></a>');
		if (t.search) a.addClass('top_button_search');
		a.data("title", t.title);
		a.data("items", t.items);
		a.data("t", t);
		a.data("keyNavRemoveSelected", true);
		
		$(a).pressurize();
				
		a[0].onclick = function (ev, triggered) {			
			activateTab($(this), null, triggered); 
		};
		
		
		t.tab = a;
		
        a.html(t.title);
		
		if(selectedTabTex && t.title == selectedTabTex) {
			firsClickableTab = a;
		}
		
		if(firsClickableTab == null)
			firsClickableTab = a;
		
		tabs.append(a);
	}
		
	return firsClickableTab;
}

function videoPlayAllowed() {
	var videoPlayAllowed = false;
	var currConn = ConnectionMonitor.getMyNetworkType();
	
	if (wifionly && currConn != "WLAN") return false;
	
	for (type in ALLOWED_CONNECTION_TYPES) {
		if (ALLOWED_CONNECTION_TYPES.hasOwnProperty(type)) {
			if ((type == currConn) && (ALLOWED_CONNECTION_TYPES[type] == true)) {
				videoPlayAllowed = true;
				break;
			}
		}
	}
	logDebug("Checked if video playback is allowed on connection: " + currConn + ", allowed: " + videoPlayAllowed);
	return videoPlayAllowed;
}

function updateNetworkStatus(){
	var conn = ConnectionMonitor.getMyNetworkType();
	logDebug("Network connection changed: " + conn);
	// update it in the WRT widget
	get("bar_network_indicator").removeClass("offline");
	get("bar_network_indicator").removeClass("wifi");
	get("bar_network_indicator").removeClass("3G");
	get("bar_network_indicator").removeClass("2G");
	if (ConnectionMonitor.isWiFi(conn)) {
		get("bar_network_indicator").addClass("wifi");
		playerConn = "wifi";
	} else if (ConnectionMonitor.is3G(conn)) {
		get("bar_network_indicator").addClass("g3");
		playerConn = "3g";
	} else if (ConnectionMonitor.is2G(conn)) {
		get("bar_network_indicator").addClass("g2");
		playerConn = "2g";
	} else if (conn == "OFFLINE") {
		get("bar_network_indicator").addClass("offline");
		playerConn = "offline";
	} else {
		playerConn = "unknown";
	}
	
	// update it in the video player as well
	updateConnectionMode(playerConn);
}

// addSysInfo and removeSysInfo methods are a workaround. The sysinfo embed drains first key event so when the Video player is shown the first tap didn't do
// anything but focused the Video player. Only second event got processed by the Video player which was annoying. 
function addSysInfo() {
	// the sysinfo plugin is used to trigger vibra feedback; other system information go over Platform Services
	$("#sysinfo_container").html('<embed id="sysinfo1" type="application/x-systeminfo-widget" hidden="yes" style="position:absolute; top: -500px; height:1; width:1;z-index:-200;"></embed>');
	sysinfo__ = document.getElementById("sysinfo1");

	logDebug("Added sysinfo, html: " + $("#sysinfo_container").html() + ", sysinfo__: " + sysinfo__ ? null : "avail");
}
function removeSysInfo() {
	logDebug("Removing sysinfo");

	$("#sysinfo_container").empty();
	sysinfo__ = null;
}

function startvibra() {
	logDebug("Triggering tactile feedback");
	if (sysinfo__ && phone) {
		setTimeout(function(){
			try {
				sysinfo__.startvibra(10, 10);
			} catch (e) {
				// silently ignore since, tactile feedback won't be working
				logDebug("Tactile feedback not available (exception)");
			}
		}, 0);
	} else {
		logDebug("Tactile feedback not available (null)");
	}
}

function logDebug(str) {
	if (DEBUG) {
		get("debug_view").append(str + "<br>");
		get("debug_view").attr({ scrollTop: get("debug_view").attr("scrollHeight") });
	}
}

function truncateText(text, maxNumberOfCharacters) {
	var output = "";
	if(text.length > maxNumberOfCharacters) {
		for(var i = maxNumberOfCharacters + 2; i > 10; i--) {
			if(text.charAt(i) == " ") {
				break;
			}
		}
		output = text.substring(0,i) + "...";
	} else {
		output = text;	
	}
	return output;
}

function exit() {
	rightMenu.hide(true);
	window.close();
}

function get(id) {
	return $(document.getElementById(id));
}